//author: create by SunJH
//时间: 2021/11/22 0022
//邮箱: 965989158@qq.com
//描述: 网络请求管理器，在这里统一处理，封装网络请求

import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:get/get.dart'hide Response;

import 'http_config.dart';
import 'interceptors/my_log_interceptor.dart';
import 'interceptors/token_interceptor.dart';
import 'result_bean.dart';

class HttpUtil {
  static final HttpUtil _instance = HttpUtil._internal();
  TokenInterceptors? _tokenInterceptors;
  var decode = json.decode(r'{"msg":"网络请求错误","code":-1}');
  final Dio _dio = Dio();
  //通用全局单例，第一次使用时初始化
  HttpUtil._internal() {
    _dio.options.baseUrl = HttpConfig.baseUrl;
    _dio.options.connectTimeout = HttpConfig.kConnectTimeout;
    _dio.options.receiveTimeout = HttpConfig.kReceiveTimeout;
    _dio.options.sendTimeout = HttpConfig.kSendTimeout;
    _dio.interceptors.add(MyLogInterceptor());
  }

  static HttpUtil getInstance() => _instance;

  Dio get client => _dio;

  void setToken(String token){
    _tokenInterceptors = TokenInterceptors(token);
    _dio.interceptors.add(_tokenInterceptors!);
  }
  void deleteToken(){
    _dio.interceptors.remove(_tokenInterceptors);
  }
  void rebase(String baseIp) {
    _dio.options.baseUrl = baseIp;
  }

  Future<ResultBean<T?>> get<T>(String url,
      { JsonParse<T>? jsonParse, Map<String, dynamic>? params}) async {
    String? errorMsg;
    Response response;
    try{
      response = await _dio.get(url, queryParameters: params);
    }on DioError catch(e){
      print(e.toString());
      return ResultBean.error(decode);
    }
    //TODO 需要提取出来，post请求和get请求共用同一个数据解析
    if (errorMsg != null ) {
      return ResultBean.error(decode);
    }
    switch (response.data['code']) {
      case 200:
        return ResultBean.fromData(response.data, jsonParse);
      case 401:{
        // token 过期，需要跳转到登录页面
        // Get.toNamed(TLYJUnitRouter.login);TODO 请求错误的统一处理未做
        return ResultBean.error(response.data);
      }
      default:
        return ResultBean.error(response.data);
    }
  }

}
